<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    width="750px"
    :body-style="{ height: '500px' }"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';

  import { ledViewFormSchema } from './ledview.data';
  import { getLedView, addLedView, updateLedView } from '/@/api/cms/ledview';
  import { LedViewDto } from '/@/api/cms/model/ledViewModel';

  import { useMessage } from '/@/hooks/web/useMessage';

  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'AddOrUpdateLedView',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();

      /**
       * 显示的模块标题，用于显示在弹出框中的标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: ledViewFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log(data);
        //接收父组件传递的数据
        if (data != undefined && data != null) {
          qcUnifyProps.value = unref(data);
        }

        resetFields(); //重置表单
        setModalProps({ confirmLoading: false });

        // 如果是修改数据，根据传入的id获取数据后进行赋值
        if (qcUnifyProps.value.operateType == OperationTypeEnum.EDIT) {
          getLedView(qcUnifyProps.value?.dataId)
            .then((res) => {
              console.log('res', res);
              //解析内容json进行赋值
              let data = {
                id: res.id,
                name: res.name,
                fixed: res.fixed,
                begintm: res.begintm,
                endtm: res.endtm,
                imageId: [],
                content: '',
                title: '',
                fontSize: '',
                scrollStep: 1, //文字滚动速度默认为1
              };
              if (res.content != undefined && res.content != null && res.content.length > 0x0) {
                try {
                  //转换json对象失败不进行赋值
                  let contentJsonObject = JSON.parse(res.content);
                  if (contentJsonObject != undefined && contentJsonObject != null) {
                    data.title = contentJsonObject.title;
                    data.content = contentJsonObject.content;
                    data.fontSize = contentJsonObject.fontSize;
                    // data.imageId = contentJsonObject.imageId;
                    data.scrollStep = contentJsonObject.scrollStep;
                    data.imageDisplayType = contentJsonObject.imageDisplayType;
                    let imageObj = {
                      id: contentJsonObject.imageId,
                      name: contentJsonObject.imageName,
                      type: contentJsonObject.imageType,
                    };
                    data.imageId.push(imageObj);
                  }
                } catch (e) {
                  // console.err(e);
                }
              }

              setFieldsValue({
                ...data,
              });
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        }
      });

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        //对应操作的步骤为：验证表单、提交后台保存、关闭modal、调用父组件事件刷新数据
        //数据验证和处理方法一致
        const values = await validate();
        setModalProps({ confirmLoading: true });
        //对界面输入的数据进行json处理，后台接收最终的json字符串
        //获取上传图片中的图片id、name、type，可以没有
        let imageId = 0;
        let imageName = '';
        let imageType = '';
        if (values.imageId != undefined && values.imageId != null) {
          if (values.imageId.length > 0x0) {
            //如果是数组，表示是上传的图片文件信息，获取第1个文件信息中的图片id
            imageId = values.imageId[0x0].id;
            imageName = values.imageId[0x0].name;
            imageType = values.imageId[0x0].type;
          } else {
            //如果不是数组，表示是修改，直接使用原有的值
            imageId = values.imageId;
          }
        }
        console.log('values', values);
        let contentJsonObject = {
          title: values.title,
          content: values.content,
          fontSize: values.fontSize,
          imageId: imageId,
          imageName: imageName,
          imageType: imageType,
          scrollStep: values.scrollStep,
          imageDisplayType: values.imageDisplayType,
        };
        let data: LedViewDto = {
          id: values.id,
          name: values.name,
          fixed: values.fixed,
          begintm: values.begintm,
          endtm: values.endtm,
          content: JSON.stringify(contentJsonObject),
        };
        if (qcUnifyProps.value.operateType == OperationTypeEnum.ADD) {
          try {
            //调用接口进行保存
            addLedView(data)
              .then((res) => {
                if (!res || Object.keys(res).length == 0) {
                  createMessage.success('保存成功。', 2);
                }
                opSuccess();
              })
              .catch((ex) => {
                console.log('catch ', ex);
                createMessage.error(ex.msg);
              });
          } finally {
            setModalProps({ confirmLoading: false });
          }
        } else if (qcUnifyProps.value.operateType == OperationTypeEnum.EDIT) {
          //调用接口进行保存
          updateLedView(data)
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('修改成功。', 2);
              }
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } else {
          createMessage.error('当前操作类型错误，无法进行对应操作。', 5);
        }
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }

      return {
        displayModuleTitle,
        registerModal,
        registerForm,
        onButtonOkClick,
        opSuccess,
      };
    },
  });
</script>
